package yxk.service.configm;

import com.alibaba.fastjson.JSONObject;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.workflow.engine.msg.AbstractMessageServiceHandler;
import kd.bos.workflow.engine.msg.ctx.MessageContext;
import kd.bos.workflow.engine.msg.info.ToDoInfo;
import yxk.report.esc.hssc.UserInformatioReport;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 飞书代办消息
 */
public class FeiShuHandler extends AbstractMessageServiceHandler {
    private static final Log LOG = LogFactory.getLog(UserInformatioReport.class);
    private static final String CHANNELTYPE="feishu";

    private static FeiShuService feiShuService=new FeiShuService();
    /**
     *       流程节点任务，创建待办；
     * @param messageContext
     * @param toDoInfo
     */
    @Override
    public void createToDo(MessageContext messageContext, ToDoInfo toDoInfo) {
        LOG.info("messageContext:{}",messageContext);
        LOG.info("toDoInfo:{}",toDoInfo);
        Long taskId = messageContext.getTaskId();//当前任务ID
        String toKen = feiShuService.getToKen();//飞书token
        Map<String, String> mapUser = FeiShuService.getUserPhones(toDoInfo.getUserIds());//获取人员电话号码
        List<String > userPhones=new ArrayList<>();
        for (String s : mapUser.keySet()) {
            userPhones.add(s);
        }
        Map<String, String> personID = feiShuService.getPersonID(userPhones, toKen);//根据电话号码获取飞书人员ID
        QFilter qF=new QFilter("currenttaskid", QCP.equals,taskId);
        DynamicObject execution = BusinessDataServiceHelper.loadSingle("wf_execution","startuserid",qF.toArray());
        //获取提交人
        DynamicObject startuser = BusinessDataServiceHelper.loadSingle(execution.getLong("startuserid"), "bos_user");
        String url = toDoInfo.getUrl();

        if(personID != null && personID.size() > 0){
            for (String s : personID.keySet()) {
                String id = personID.get(s);
                String number = mapUser.get(s);
                //流程实例
                 JSONObject body = feiShuService.getBodyMethod(id, toDoInfo.getContent(), startuser.getString("name"), url+"&userNumber="+number);
                feiShuService.createWorkflow(body,toKen);
            }

        }
    }

    /**
     *   流程处理待办任务；
     * @param messageContext
     * @param toDoInfo
     */
    @Override
    public void dealToDo(MessageContext messageContext, ToDoInfo toDoInfo) {

    }
    /**
     *   工作流中撤回，或者多人收到任务，其中一人审批，删除其他人的待办时，调用此接口；
     * @param messageContext
     * @param toDoInfo
     */
    @Override
    public void deleteToDo(MessageContext messageContext, ToDoInfo toDoInfo) {

    }
}
